{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# nonogram_default_search"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/nonogram_default_search.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/nonogram_default_search.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Nonogram  (Painting by numbers) in Google CP Solver.\n",
    "\n",
    "  http://en.wikipedia.org/wiki/Nonogram\n",
    "  '''\n",
    "  Nonograms or Paint by Numbers are picture logic puzzles in which cells in a\n",
    "  grid have to be colored or left blank according to numbers given at the\n",
    "  side of the grid to reveal a hidden picture. In this puzzle type, the\n",
    "  numbers measure how many unbroken lines of filled-in squares there are\n",
    "  in any given row or column. For example, a clue of '4 8 3' would mean\n",
    "  there are sets of four, eight, and three filled squares, in that order,\n",
    "  with at least one blank square between successive groups.\n",
    "\n",
    "  '''\n",
    "\n",
    "  See problem 12 at http://www.csplib.org/.\n",
    "\n",
    "  http://www.puzzlemuseum.com/nonogram.htm\n",
    "\n",
    "  Haskell solution:\n",
    "  http://twan.home.fmf.nl/blog/haskell/Nonograms.details\n",
    "\n",
    "  Brunetti, Sara & Daurat, Alain (2003)\n",
    "  'An algorithm reconstructing convex lattice sets'\n",
    "  http://geodisi.u-strasbg.fr/~daurat/papiers/tomoqconv.pdf\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "#\n",
    "# Make a transition (automaton) list of tuples from a\n",
    "# single pattern, e.g. [3,2,1]\n",
    "#\n",
    "def make_transition_tuples(pattern):\n",
    "  p_len = len(pattern)\n",
    "  num_states = p_len + sum(pattern)\n",
    "\n",
    "  tuples = []\n",
    "\n",
    "  # this is for handling 0-clues. It generates\n",
    "  # just the minimal state\n",
    "  if num_states == 0:\n",
    "    tuples.append((1, 0, 1))\n",
    "    return (tuples, 1)\n",
    "\n",
    "  # convert pattern to a 0/1 pattern for easy handling of\n",
    "  # the states\n",
    "  tmp = [0]\n",
    "  c = 0\n",
    "  for pattern_index in range(p_len):\n",
    "    tmp.extend([1] * pattern[pattern_index])\n",
    "    tmp.append(0)\n",
    "\n",
    "  for i in range(num_states):\n",
    "    state = i + 1\n",
    "    if tmp[i] == 0:\n",
    "      tuples.append((state, 0, state))\n",
    "      tuples.append((state, 1, state + 1))\n",
    "    else:\n",
    "      if i < num_states - 1:\n",
    "        if tmp[i + 1] == 1:\n",
    "          tuples.append((state, 1, state + 1))\n",
    "        else:\n",
    "          tuples.append((state, 0, state + 1))\n",
    "  tuples.append((num_states, 0, num_states))\n",
    "  return (tuples, num_states)\n",
    "\n",
    "\n",
    "#\n",
    "# check each rule by creating an automaton and transition constraint.\n",
    "#\n",
    "def check_rule(rules, y):\n",
    "  cleaned_rule = [rules[i] for i in range(len(rules)) if rules[i] > 0]\n",
    "  (transition_tuples, last_state) = make_transition_tuples(cleaned_rule)\n",
    "\n",
    "  initial_state = 1\n",
    "  accepting_states = [last_state]\n",
    "\n",
    "  solver = y[0].solver()\n",
    "  solver.Add(\n",
    "      solver.TransitionConstraint(y, transition_tuples, initial_state,\n",
    "                                  accepting_states))\n",
    "\n",
    "\n",
    "def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver('Nonogram')\n",
    "\n",
    "  #\n",
    "  # variables\n",
    "  #\n",
    "  board = {}\n",
    "  for i in range(rows):\n",
    "    for j in range(cols):\n",
    "      board[i, j] = solver.IntVar(0, 1, 'board[%i, %i]' % (i, j))\n",
    "\n",
    "  board_flat = [board[i, j] for i in range(rows) for j in range(cols)]\n",
    "\n",
    "  # Flattened board for labeling.\n",
    "  # This labeling was inspired by a suggestion from\n",
    "  # Pascal Van Hentenryck about my (hakank's) Comet\n",
    "  # nonogram model.\n",
    "  board_label = []\n",
    "  if rows * row_rule_len < cols * col_rule_len:\n",
    "    for i in range(rows):\n",
    "      for j in range(cols):\n",
    "        board_label.append(board[i, j])\n",
    "  else:\n",
    "    for j in range(cols):\n",
    "      for i in range(rows):\n",
    "        board_label.append(board[i, j])\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  for i in range(rows):\n",
    "    check_rule(row_rules[i], [board[i, j] for j in range(cols)])\n",
    "\n",
    "  for j in range(cols):\n",
    "    check_rule(col_rules[j], [board[i, j] for i in range(rows)])\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  parameters = pywrapcp.DefaultPhaseParameters()\n",
    "  parameters.heuristic_period = 200000\n",
    "\n",
    "  db = solver.DefaultPhase(board_label, parameters)\n",
    "\n",
    "  print('before solver, wall time = ', solver.WallTime(), 'ms')\n",
    "  solver.NewSearch(db)\n",
    "\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    print()\n",
    "    num_solutions += 1\n",
    "    for i in range(rows):\n",
    "      row = [board[i, j].Value() for j in range(cols)]\n",
    "      row_pres = []\n",
    "      for j in row:\n",
    "        if j == 1:\n",
    "          row_pres.append('#')\n",
    "        else:\n",
    "          row_pres.append(' ')\n",
    "      print('  ', ''.join(row_pres))\n",
    "\n",
    "    print()\n",
    "    print('  ', '-' * cols)\n",
    "\n",
    "    if num_solutions >= 2:\n",
    "      print('2 solutions is enough...')\n",
    "      break\n",
    "\n",
    "  solver.EndSearch()\n",
    "  print()\n",
    "  print('num_solutions:', num_solutions)\n",
    "  print('failures:', solver.Failures())\n",
    "  print('branches:', solver.Branches())\n",
    "  print('WallTime:', solver.WallTime(), 'ms')\n",
    "\n",
    "\n",
    "#\n",
    "# Default problem\n",
    "#\n",
    "# From http://twan.home.fmf.nl/blog/haskell/Nonograms.details\n",
    "# The lambda picture\n",
    "#\n",
    "rows = 12\n",
    "row_rule_len = 3\n",
    "row_rules = [[0, 0, 2], [0, 1, 2], [0, 1, 1], [0, 0, 2], [0, 0, 1], [0, 0, 3],\n",
    "             [0, 0, 3], [0, 2, 2], [0, 2, 1], [2, 2, 1], [0, 2, 3], [0, 2, 2]]\n",
    "\n",
    "cols = 10\n",
    "col_rule_len = 2\n",
    "col_rules = [[2, 1], [1, 3], [2, 4], [3, 4], [0, 4], [0, 3], [0, 3], [0, 3],\n",
    "             [0, 2], [0, 2]]\n",
    "\n",
    "if len(sys.argv) > 1:\n",
    "  file = sys.argv[1]\n",
    "  exec(compile(open(file).read(), file, 'exec'))\n",
    "main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
